<?php
/**
 * 
 * @author tangbl
 *
 */
class PublicAction extends CommonAction {
	
	//初始化
	public function _initialize() {
		parent::_initialize();
		//parent::_initmenu();
	}
	
	 //
	 public function index() {
        //如果通过认证跳转到首页
        redirect(__APP__);
    }
	
	// 用户登录页面
    public function login() {
		
        if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->display();
        }else{
            $this->redirect('Index/index');
        }
    }
	
	//动态加载优惠券规则
	public function type() {
		$type = $this->_param('val','trim','');
		$id   = $this->_param('id','intval',0);
		if($id){
			$Actyhj  =  D("Actyhj");
			$data    = $Actyhj->find($id);
			$attr    = json_decode($data['attr'],true);
		}else{
			$attr = '';
		}
		
		$this->assign("type",$type);
		$this->assign("attr",$attr);
		$this->display();
	}
	
	
	//用户登陆操作
    public function checkLogin(){
		
		$username =  $this->_post('username');
        $password =  $this->_post('password');
        //$verify   = $this->_post('verify');
		
        //生成认证条件
        $map             =   array();
        // 支持使用绑定帐号登录
        $map['username'] = $username;
        $map['status']   = 1;
		
        /*if(session('verify') != md5($verify)) {
            $this->error('验证码错误！');
        }*/
        import('ORG.Util.RBAC');
        $authInfo = RBAC::authenticate($map);
		
        //使用用户名、密码和状态的方式进行认证
        if(false == $authInfo) {
            $this->error(L('pbc_validate_no_exsits'));
        }else {
            if($authInfo['password'] != myencrypt($password) ) {
                $this->error(L('pbc_validate_pwd_error'));
            }
			session(C('USER_AUTH_KEY'), $authInfo['id']);
            session('userid',$authInfo['id']);
			session('username',$authInfo['username']);
            session('role',$authInfo['role']);
            
            $expire = C("COOKIE_KEEP_TIME");
			if(empty($authInfo['skin'])){
				$authInfo['skin'] = 'default';
			}
			session('skin',$authInfo['skin']);
			cookie('style_color',$authInfo['skin'],$expire);
			if(empty($authInfo['lang'])){
				$default_lang = C('DEFAULT_LANG');
			}else{
				$default_lang = $authInfo['lang'];
			}
			cookie('think_language',$default_lang,$expire);
			
            if($authInfo['username']==C('SPECIAL_USER')) {
                session(C('ADMIN_AUTH_KEY'), true);
				session('roleid',C('SPECIAL_USER'));	
            }else{
				session('roleid',$authInfo['role']);
			}
            
            //保存登录信息
            $User	=	M(C('USER_AUTH_MODEL'));
            $ip		=	get_client_ip();
            $data = array();
            if($ip){
                import('ORG.Net.IpLocation');
                $Ip = new IpLocation();
                $location = $Ip->getlocation($ip);
                $data['last_location'] = '';
                if($location['country'] && $location['country']!='CZ88.NET') $data['last_location'].=$location['country'];
                if($location['area'] && $location['area']!='CZ88.NET') $data['last_location'].=' '.$location['area'];
            }
            $data['id']	=	$authInfo['id'];
            $data['last_login_time']	=	time();
            $data['last_login_ip']	=	get_client_ip();
            $User->save($data);
            
            wlog("1","用户登陆:".$username);//记录日志
			
            // 登陆缓存
            RBAC::getAccessAction();
			RBAC::getAccessMenu();
            redirect(U("Index/index"));
        }
	}

    /**
     * 用户登出
     */
    public function logout() {
 
		$authId = $_SESSION[C('USER_AUTH_KEY')];
		$roleId = $_SESSION['roleid'];
		S("_menutree".$roleId,NULL);	
		S("_accessaction".$authId,NULL);
			
		//wlog("User","logout",$authId);//记录日志
			
		unset($_SESSION[C('USER_AUTH_KEY')]);
		unset($_SESSION['roleid']);
		unset($_SESSION);
		session_destroy();
        $this->success(L('pbc_login_logout'),__URL__.'/login/');
    }
	
	//根据lang读取栏目
	public function ajax(){
		$lang   = $this->_param("lang");
		$module = $this->_param("module");
		if($lang){
			$pid    = 0 ;
			$cateid = $this->_param("cateid","intval",0);
			$data   = D("Category");
			$cates  = $data->getCateByModule($lang);
			
			if($module){
				$selects = get_select_module($cates,$pid,$cateid,$module);
			}else{
				$selects = get_cate_select($cates,$pid,$cateid);
			}
			$this->ajaxReturn($selects);
		}else{
			$this->ajaxReturn("");
		}
	}
	
	//读取父栏目
	public function ajax_menu(){
		$pid = $this->_param("pid","intval",0);
		if($pid){
			$data  = D("Category");
			$rows  = $data->find($pid);
			$this->ajaxReturn($rows);	
		}else{
			$this->ajaxReturn("");	
		}
	}
	
	//得到已经存在模块分类
	public function getExsitsModule(){
		$lang   = $this->_param("lang");
		$flag   = $this->_param("flag");
		if($lang){
			$rows  = array();
			if($flag){
				$data  = D("Category");
				$lists  = $data->getExsitsModule($lang);
				foreach($lists as $v){
					$rows[] = $v['module'];
				}
			}
			$all   = C("GLOBAL_CATEGORY");
			$html  = '<option value="">'.L("cfg_form_tis_select").'</option>';
			foreach($all as $v){
				if(in_array($v[0],$rows)){
					$html .= '<option value="'.$v[0].'" disabled>'.L($v[1]).'</option>';
				}else{
					$html .= '<option value="'.$v[0].'">'.L($v[1]).'</option>';
				}
			}
			$this->ajaxReturn($html);
		}else{
			$this->ajaxReturn("");
		}
	}
	
	//编辑回复-加载关键字8
	public function add_keywrods(){
		$keywords = $this->_param("keywords");
		$this->assign("keywords",$keywords);
		$this->display();
	}
	
	//加载关键字9
	public function content_add_keywrods(){
		$this->display();
	}
	
	//加载地理位置10
	public function content_add_location(){
		$keywords   = $this->_param("keywords","","");
		$islocation = $this->_param("islocation","intval",2);
		$this->assign("islocation",$islocation);
		$this->assign("keywords",$keywords);
		$this->display();
	}
	
	//加载事件类型11
	public function content_add_event(){
		$keywords = $this->_param("keywords");
		$event    = $this->_param("event");
		
		//if(empty($solevar)){
			$replyCont  = D('Reply');
			$where      = "reply_type=3 and event_type<3";
			$lists      = $replyCont->field("event_type")->where($where)->select();
		/* }else{
			$replyCont  = D('ReplyContent');
			$where      = "content_solevar='$solevar' and reply_type=3 and event_type<3";
			$lists      = $replyCont->field("event_type")->where($where)->select();
		} */
		$rows = array();
		foreach($lists as $v){
			$rows[] = $v['event_type'];	
		}
		
		$event_type_str = '';
		foreach(C('EVENT_TYPE') as $k=>$v){
			if(!in_array($k,$rows)||($k==$event)){
				$event_type_str .= '<option value="'.$k.'" >'.L($v).'</option>';
			}else{
				$event_type_str .= '<option value="'.$k.'" disabled="disabled">'.L($v).'</option>';	
			}
		}
		
		$this->assign("event_type_str",$event_type_str);
		$event = $this->_param("event");
		$this->assign("event_type",$event);
		$this->display();
	}
	
	//加载自定义菜单12
	public function content_add_menu(){
		
		
		$value  = $this->_param("value");
		$solevar    = $this->_param("solevar");
		//if(empty($solevar)){
		$replyCont  = D('Reply');
		$where      = "event_type=3";//自定义菜单
		$replys     = $replyCont->field("event_value")->where($where)->select();
		/* }else{
			$replyCont  = D('ReplyContent');
			$where      = "content_solevar='$solevar' and event_type=3";//自定义菜单
			$replys     = $replyCont->field("event_value")->where($where)->select();
		} */
		$arrays     = array();
		foreach($replys as $v){
			if($v['event_value']!=$value)
			$arrays[] = $v['event_value'];	
		}
		
		$json   = F("Wxmenu");
		foreach($json as $v){
			if(is_array($v['sub_button'])){
				$html .= "<option disabled>".$v['name']."</option>";	
				foreach($v['sub_button'] as $k){
					
					$dis = "";
					if($k['type']=="view" || in_array($k['key'],$arrays)){
						$dis = "disabled";
					}
					$html .= "<option value='".$k['key']."' ".$dis.">├─".$k['name']."</option>";	
				}
			}else{
				$dis = "";
				if($k['type']=="click" || in_array($k['key'],$arrays)){
					$dis = "disabled";
				}
				$html .= "<option value='".$v['key']."' ".$dis.">".$v['name']."</option>";	
			}	
		}
		$this->assign("content_add_menu",$html);
		
		$this->assign("menu_type",$value);
		$this->display();
		
	}
	
	//添加lbs信息点
	public function lbs_add() {
		$id = $this->_get("id","intval",0);
		if($id){
			$model = M("Outlet");
			$row   = $model->find($id);
			$this->assign("row",$row);
		}else{
			$address = $this->_param("address","trim","");
			if(empty($address)){
				$address = C("MAP_DEFAULT_ADDR");
			}
			$this->assign("address",$address);
		}
		
		$this->display();
	}
	
	//生成微信自动菜单
	public function chat_menu(){
		
		import('ORG.Wechat.ThinkWechatMenu');
		$APP_ID     = trim(get_syscfig_key('wxappid'));
		$APP_SECRET = trim(get_syscfig_key('wxsecret'));
		$menu = new ThinkWechatMenu($APP_ID,$APP_SECRET);
		
		$json   = F("Wxmenu");
		$rows   = array();
		foreach($json as $k=>$v){
			
			$rows[$k]['name'] = $v['name'];
			$sub = $v['sub_button'];
			
			if(is_array($sub)){
				foreach($sub as $a=>$b){
					if($b['type'] == "view"){
						$b['url'] = $b['key'];
						unset($b['key']);
					}
					$rows[$k]['sub_button'][$a] = $b ;
				}
			}
		}
		$output = $menu->Run($rows);
		$array  = json_decode($output,true);
		$this->ajaxReturn($array);
	}
	
	/**
	 * 节点(模块对应的操作方法)
	 */
	public function node(){
		
		$module = $this->_param("module");
		$node   = D("Node");
		$afuncs = $node->getFunctions($module);
		
		$param['level'] = 1 ;
		$param['name']  = $module ;
		$efunc  = $node->getExsitsFun($param);
		
		load("@.node");
		$nodes = return_array($module);
		$rows  = array();
		foreach($afuncs as $v){
			if(in_array($v,$efunc)){
				$rows[] = array("name"=>$v,"show"=>false);	
			}else{
				$rows[] = array("name"=>$v,"show"=>true,"lang"=>$nodes[$v]);
			}
		}
		$this->success($rows);
	}
	
	//node语言包
	public function lang(){
		$lang = D("Lang");
		$node = D("Node");
		$list = $lang->select();
		
		foreach($list as $v){
			$langval         = $v['langval'];
			$data['langval'] = str_replace("zh-cht","zh-tw",$langval);	
			$where = "title = '".$v['key']."'";
			$vals = $node->where($where)->save($data);
		}	
		exit('ok');
	}
    
	//显示验证码
    public function verify() {
        $type	=	isset($_GET['type'])?$_GET['type']:'gif';
        import("ORG.Util.Image");
        Image::buildImageVerify(4,1,$type);
    }
	
	//获取附属模型表单元素
	public function getAttachedModule(){
		$module_id = $this->_get("moduleid");
		$solevar = $this->_get("solevar");
		$module    = M("Module");
		$row = $module->where("module_name='$module_id'")->find();
		$html = '';
		
		//查附属模型数据
		$adata = M(ucfirst($module_id))->where("solevar='$solevar'")->find();
		//print_r($adata);
		//exit();
		
		if($module_id && $row['id']){
			$id    = $row['id'];
			$where = "module_id =".$id;
			$Module_filed = M('Module_filed');
			$Module_filed_data = $Module_filed->where($where)->order('order_num DESC')->select();
			if($Module_filed_data){
				foreach($Module_filed_data as $k=>$v){
					$filed_attr = json_decode($v['filed_attr'],true);
					
					$valid_attr = json_decode($v['valid_attr'],true);
					foreach($valid_attr['tis'] as $vk=>$vv){
						$valid_attr['tis'][$vk] =  json_decode($vv,true);
					}
					
					$form['ele'][$k]['file_base']['filed_title'] = json_decode($v['filed_title'],true);
					$form['ele'][$k]['file_base']['css_class'] = $v['css_class'];
					$form['ele'][$k]['file_base']['filed_type'] = $v['filed_type'];
					$form['ele'][$k]['file_base']['tab_id'] = $v['tab_id'];
					$form['ele'][$k]['file_base']['filed_name'] = $v['filed_name'];
					
					$form['ele'][$k]['filed_attr'] = $filed_attr;
					$form['ele'][$k]['filed_attr']['default'] = @$adata[$v['filed_name']];
					$form['ele'][$k]['valid_attr'] = $valid_attr;
				}
			}
			
			import('ORG.Module.ThinkFrom');
			$form_obj = new ThinkForm($form);
			$html = $form_obj->createAttached();
		}
		echo $html;
	}
	
	//查找门店
	public function mapOutlet(){
	
		$type = $this->_param("type","","area");
		$flag = 1;
		$info = "";
		$area = $this->_param("area","intval",0);
	
		if($type == "area"){
				
			$list = mapByArray($area,"area");
				
		}elseif($type == "address"){
				
			$addr = $this->_param("address","urldecode");
			$poin = mapAddressToPoi($addr);
			if($poin){
				$poit = $poin['lng'].",".$poin['lat'];
				$list = mapNearby(array("location"=>$poit));
			}
			//没有找到周边门店,默认读取区门店
			if(empty($list)){
				$list = mapByArray($area,"area");
			}
		}
	
		if(empty($list)){
			$info = "该区域没有找到对应的门店";
			$flag = 0;
		}
	
		$this->ajaxReturn($list,$info,$flag);
	}
}